/*
 * util.js
 * 工具类
 */
import axios from "axios"
import qs from "qs"
import APP from "./appConfig"
import { Indicator } from 'mint-ui';
const baseParam = {
 
}
const uleUrl=APP.DOMAIN
/* 一些请求的全局配置 */
axios.defaults.baseURL = APP.DOMAIN;
//axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.timeout = 8000;
/* GET请求 */
function GET(url, params) {
  url = url + fiterParams(params);
  return axios.get(url, params).then(reqResult).catch(reqErr);
}
/* POST请求 */
function POST(url, params, hasLoad = true, contentType = 'application/json') {
  if (hasLoad)
  return axios.post(url, { ...baseParam, ...params }, { headers: { 'Content-Type': contentType } }).then(reqResult).catch(reqErr);;
}
function fiterParams(params) {
  let urlmix = '';
  if (params) {
    let paramstr = '';
    if (typeof params === 'string') urlmix = '/' + params;
    if (typeof params === 'object') {
      paramstr = qs.stringify(params);
      urlmix = '?' + paramstr;
    }
  }
  return urlmix;
}
function JSONP(url, params, hasLoad = true) {
  Indicator.open({
    text: '正在加载...',
    spinnerType: 'fading-circle',//'snake''fading-circle''double-bounce''triple-bounce'
  });
   return $.ajax({
    url: uleUrl+url, 
    type: "get",
    dataType: "jsonp",
    data:{...params},
    jsonp: "jsoncallback",
  }).then((res)=>{
    Indicator.close();
    return res
  }).catch((err)=>{
    Indicator.close();
    return err
  })
}
function JsonpPost(url, params, hasLoad = true) {
  let contentType = 'application/json'
  
  return $.ajax({
   url: uleUrl+url, 
   type: "post",
   data:{...params},
   headers: { 'Content-Type': contentType },
 }).then((res)=>{
   return res
 }).catch((err)=>{
   return err
 })
}
function reqResult(res) {
  let data = null;
  if (res.status === 200) {//&& res.statusText. toLowerCase() == 'ok'
    //console.log('req res', res.data);
    if (res.data && res.data.code)
      data = res.data.data;
    else { throw { code: res.data.code, msg: res.data.msg } }
  } else { throw 'Request failed, ' + JSON.stringify(res); }
  return data;
}
function reqErr(e) {
  console.error('Request error:', e);
  if (e && e.message && e.message.toLowerCase().indexOf('timeout') > -1)
    e = { code: 0, msg: '请求超时,请稍候再试' }
  throw e;
}
function _getDate(datetime) {
  if (typeof datetime == 'string') {
    let arr = datetime.split(/[- : \/ T]/);
    if (arr[0].length === 4) arr[1] = arr[1] - 1;
    datetime = new Date(...arr);
  }
  return datetime;
}
/*
 * 时间格式化
 * datetime:String,必须,要格式化的时间字符串
 * format:String,可无,时间的格式(注意格式中对应的字母),默认为'yyyy-MM-dd HH:mm:ss' 全角ｍ表示英文月份
 */
function DateFormat(datetime, format = 'yyyy-MM-dd HH:mm:ss') {
  let date = datetime,
    month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  try {
    date = _getDate(date);
    var o = {
      'ｍ+': month[date.getMonth()],
      "M+": date.getMonth() + 1, //月份 
      "d+": date.getDate(), //日 
      "H+": date.getHours(), //小时 
      "m+": date.getMinutes(), //分 
      "s+": date.getSeconds(), //秒 
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return format;
  } catch (e) { return datetime; }
}

/*
 * 时间差(用于倒计时)
 * type:String,可无,结果类型,默认为'H',可选值:'d'天,'H'时,'m'分,'s'秒
 * source:String|Object(Date),可无,源时间,默认为当前时间
 * destination:String|Object(Date),可无,目标时间,默认为当前时间
 * source与destination 必须同时有一个有值
 * 返回值null|{s:秒,m:分,H:时,d:天}(若为负值则表示时间指向反了)
 */
function DateDiff({ type = 'H', source = new Date(), destination = new Date() } = {}) {
  let date = source, ts = 0;
  try {
    date = _getDate(date);
    destination = _getDate(destination);
    ts = destination.getTime() - date.getTime();//Math.abs(destination.getTime() - date.getTime());
    //console.log('sTs:%s,dTs:%s,ts:%s', date.getTime(), destination.getTime(), ts);
    let o = {
      s: Math.floor(ts / 1000),
      m: Math.floor(ts / 60000),//1000*60
      H: Math.floor(ts / 3600000),//1000*60*60
      d: Math.floor(ts / 86400000)//1000*60*60*24
    }

    switch (type) {
      case 'H':
      default:
        return { s: o.s % 60, m: o.m % 60, H: o.H, d: 0 };
      case 's':
        return { s: o.s, m: 0, H: 0, d: 0 };
      case 'm':
        return { s: o.s % 60, m: o.m, H: 0, d: 0 };
      case 'd':
        return { s: o.s % 60, m: o.m % 60, H: o.H % 24, d: o.d };
    }
  } catch (e) { return null; }
}

/*
 * 时间差值格式化
 * 大于24小时显示日期
 * 大于60分钟显示n小时前
 * 大于1分钟显示n分钟前
 * 否则显示刚刚
 */
function DateDiffFormat(datetime, format = 'yyyy.MM.dd') {
  let diff = DateDiff({ source: datetime }), result = '';
  // console.log(datetime, diff);
  if (diff) {
    if (diff.H >= 24) {
      result = DateFormat(datetime, format);
    } else {
      if (diff.H > 0)
        result = diff.H + '小时前';
      else {
        if (diff.m > 1) result = diff.m + '分钟前';
        else result = '刚刚';
      }
    }
  }
  return result;
}

function DateBetween({ source = new Date(), begin, end } = {}) {
  let isBetween = false;
  try {
    begin = _getDate(begin);
    end = _getDate(end);
    return begin <= source && end >= source;
  } catch (e) { }
  return isBetween;
}

/*
* 判断图片是否为GIF格式
*/
function endWithGif(str) {
  if (str) {
    let pos = str.lastIndexOf('.gif');
    if (pos === -1) {
      return false;
    } else {
      return pos + 4 === str.length;
    }
  }

}

export { APP, JSONP, GET, POST, DateFormat, DateDiffFormat, DateBetween, endWithGif, DateDiff, _getDate,JsonpPost }
